<?php

namespace App\Http\Controllers\Wxapi;

use Illuminate\Support\Facades\DB;
use Illuminate\Support\Str;

class ApplyController extends BaseController
{
    public function __construct()
    {
        parent::__construct();
    }

	public function getAll(){
        if ($this->result['status'] > 0){
            return $this->return_result($this->result);
        }
        $pageNo = request()->post("pageNo", 1);
        $pageSize = request()->post("pageSize", 10);
        try {
            $res = DB::table("apply_list")->select("id", "title", "start_time", "end_time", "day_count", "week_count", "month_count", "max_people_num", "each_people_num")
                ->where("status", 1)
                ->where('start_time', '<=', time())
                ->where('end_time', '>=', time())
                ->where("mall_id", request()->mallData["id"])
                ->skip(($pageNo-1) * $pageSize)->take($pageSize)->orderBy("create_time", "desc")->get();
            $res = json_decode(json_encode($res), true);
            $this->result["data"] = $this->transferFields($res);
            $beginToday = mktime(0, 0, 0, date('m'), date('d'), date('Y'));
            $endToday = mktime(0, 0, 0, date('m'), date('d') + 1, date('Y')) - 1;
            $beginWeek = date("Y-m-d H:i:s",mktime(0, 0 , 0,date("m"),date("d")-date("w")+1,date("Y")));
            $endWeek = date("Y-m-d H:i:s",mktime(23,59,59,date("m"),date("d")-date("w")+7,date("Y")));
            $beginMonth = date("Y-m-d H:i:s",mktime(0, 0 , 0,date("m"),1,date("Y")));
            $endMonth =  date("Y-m-d H:i:s",mktime(23,59,59,date("m"),date("t"),date("Y")));
            foreach ($this->result["data"] as &$item){
                $item["enable"] = true;
                if (DB::table("apply_record")->where("user_id", $this->user["id"])->where("list_id", $item["id"])
                        ->where("create_time", ">=", $beginToday)->where("create_time", "<=", $endToday)->count() > $item["dayCount"]) {
                    $item["enable"] = false;
                }elseif (DB::table("apply_record")->where("user_id", $this->user["id"])->where("list_id", $item["id"])
                        ->where("create_time", ">=", $beginWeek)->where("create_time", "<=", $endWeek)->count() > $item["weekCount"]) {
                    $item["enable"] = false;
                }elseif (DB::table("apply_record")->where("user_id", $this->user["id"])->where("list_id", $item["id"])
                        ->where("create_time", ">=", $beginMonth)->where("create_time", "<=", $endMonth)->count() > $item["monthCount"]) {
                    $item["enable"] = false;
                }elseif (DB::table("apply_record")->where("user_id", $this->user["id"])->where("list_id", $item["id"])
                        ->where("create_time", ">=", $item["startTime"])->where("create_time", "<=", $item["endTime"])->count() > $item["eachPeopleNum"]) {
                    $item["enable"] = false;
                }elseif (DB::table("apply_record")->where("list_id", $item["id"])
                        ->where("create_time", ">=", $item["startTime"])->where("create_time", "<=", $item["endTime"])->count() > $item["maxPeopleNum"]) {
                    $item["enable"] = false;
                }
                $item["startTime"] = date("Y-m-d H:i:s", $item["startTime"]);
                $item["endTime"] = date("Y-m-d H:i:s", $item["endTime"]);
            }
        }catch (\Exception $e){
            $this->result["data"] = [];
        }
        return $this->return_result($this->result);
    }

    public function getApplyInfo(){
        if ($this->result['status'] > 0){
            return $this->return_result($this->result);
        }
        $params = request()->post();
        if(empty($params["id"])){
            $this->result['status'] = 1;
            $this->result['msg'] = '申请ID不能为空';
            return $this->return_result($this->result);
        }
        try {
            $res = DB::table("apply_list as al")->leftJoin('setting_form as sf','al.form_id','=','sf.id')
                ->select("al.form_id", "sf.form_data", "al.title", "al.brief", "al.end_language")
                ->where("al.id", $params["id"])->first();
            $res = json_decode(json_encode($res), true);
            $res = $this->transferFields($res);
            $res["formData"] = json_decode($res["formData"], true);
            $this->result["data"] = $res;
        }catch (\Exception $e){
            $this->result["data"] = [];
        }
        return $this->return_result($this->result);
    }

    public function toSaveInfo(){
        if ($this->result['status'] > 0){
            return $this->return_result($this->result);
        }
        $params = request()->post();
        if(empty($params["id"])){
            $this->result['status'] = 1;
            $this->result['msg'] = '申请ID不能为空';
            return $this->return_result($this->result);
        }
        if(empty($params["formId"])){
            $this->result['status'] = 1;
            $this->result['msg'] = '表单ID不能为空';
            return $this->return_result($this->result);
        }
        if(empty($params["formData"])){
            $this->result['status'] = 1;
            $this->result['msg'] = '表单数据不能为空';
            return $this->return_result($this->result);
        }
        try {
            DB::table("apply_record")->insert([
                "list_id" => $params["id"], "form_id" => $params["formId"], "user_id" => $this->user["id"], "form_data" => $params["formData"],
                "create_time" => time(), "mall_id" => request()->mallData["id"]
            ]);
        }catch (\Exception $e){
            $this->result['status'] = 1;
            $this->result['msg'] = $e->getMessage();
            return $this->return_result($this->result);
        }
        return response()->json($this->result);
    }

    public function transferFields($data){
        if(is_array($data)){
            $newData = [];
            foreach ($data as $k => $v){
                if(!is_numeric($k)){
                    $k = Str::camel($k);
                }
                if(is_array($v)){
                    $v = $this->transferFields($v);
                }
                if(is_null($v)){
                    $v = '';
                }
                $newData[$k] = $v;
            }
            return $newData;
        }else{
            if(is_null($data)){
                return [];
            }else {
                return Str::camel($data);
            }
        }
    }
}